//
#include "stdafx.h"
#include <QDebug>
#include <filedownloader.h>
//
FileDownloader::FileDownloader(QObject* parent)
    : QObject(parent)
    , m_manager(new QNetworkAccessManager(this))
    , m_reply(nullptr)
    , m_isDownloading(false)
{
}

void FileDownloader::download(const QUrl& url, const QString& savePath)
{
    if (m_isDownloading) {
        emit error("当前已有下载任务在进行");
        return;
    }

    m_file.setFileName(savePath);
    if (!m_file.open(QIODevice::WriteOnly)) {
        emit error("无法创建文件: " + savePath);
        return;
    }

    m_reply = m_manager->get(QNetworkRequest(url));
    m_isDownloading = true;
    // 添加一些调试信息
    //if (m_reply) {
    //    qDebug() << "Network Reply created. URL:" << url;
    //    qDebug() << "Reply isFinished:" << m_reply->isFinished();
    //    qDebug() << "Reply error:" << m_reply->error();
    //    // 也可以直接连接errorOccurred信号来捕获错误
    //    connect(m_reply, &QNetworkReply::errorOccurred, this, [this](QNetworkReply::NetworkError code) {
    //        qDebug() << "Network error occurred:" << code << m_reply->errorString();
    //        });
    //}
    //else {
    //    qDebug() << "Failed to create network reply.";
    //}
    connect(m_reply, &QNetworkReply::readyRead, this, &FileDownloader::onReadyRead);
    connect(m_reply, &QNetworkReply::downloadProgress, this, &FileDownloader::onDownloadProgress);
    connect(m_reply, &QNetworkReply::finished, this, &FileDownloader::onFinished);
}

void FileDownloader::cancel()
{
    if (m_reply && m_isDownloading) {
        m_reply->abort();
    }
}

//void FileDownloader::finished(bool success, const QString& filePath)
//{
//}
//
//void FileDownloader::error(const QString& errorString)
//{
//}

void FileDownloader::onReadyRead()
{
    if (m_reply && m_file.isOpen()) {
        m_file.write(m_reply->readAll());
    }
}

void FileDownloader::onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    emit progress(bytesReceived, bytesTotal);
}

void FileDownloader::onFinished()
{
    m_isDownloading = false;
    m_file.close();

    bool success = (m_reply->error() == QNetworkReply::NoError);
    QString filePath = m_file.fileName();

    if (!success) {
        m_file.remove();
        filePath.clear();
        emit error(m_reply->errorString());
    }

    emit finished(success, filePath);
    m_reply->deleteLater();
    m_reply = nullptr;
}